package com.itshizhan.itjidancideveloper.controller.user;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.itshizhan.itjidancideveloper.dao.InviteCodeDao;
import com.itshizhan.itjidancideveloper.models.User;
import com.itshizhan.itjidancideveloper.models.vo.UserVO;
import com.itshizhan.itjidancideveloper.response.Response;
import com.itshizhan.itjidancideveloper.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController()
@RequestMapping("/user")
public class UserController {


	@Autowired
	UserService userService;

	@Autowired
	InviteCodeDao inviteCodeDao;

	@PostMapping("/register")
	public Response<UserVO> register(@RequestBody() User user,
																	 @RequestParam("inviteCode") String inviteCode){
		String account = user.getAccount();
		String nickName = user.getNickName();
		String password = user.getPassword();
		if(StrUtil.isEmpty(account)||StrUtil.isEmpty(inviteCode)){
			 return Response.fail("参数错误,注册邮箱或邀请码不能为空");
		}
		if(!Validator.isEmail(account)){
			return Response.fail("参数错误,邮箱格式不正确");
		}
		if(StrUtil.isEmpty(nickName)){
			return Response.fail("参数错误,昵称不能为空");
		}
		if(StrUtil.isEmpty(password)){
			return Response.fail("参数错误,密码应为8-20,至少包含数字和字母");
		}
		return userService.register(user, inviteCode);
	}

	@PostMapping("/login")
	public  Response<Map<String,Object>> doLogin(@RequestBody() User user){
		String account = user.getAccount();
		String password = user.getPassword();
		if(StrUtil.isEmpty(account)||StrUtil.isEmpty(password)){
			return Response.fail("账号或密码错误");
		}
		return userService.login(user);
	}

	@GetMapping("/logout")
	public  Response<String> doLogout(){
		//TODO: spring security 处理
		return Response.success();
	}

	//	@GetMapping("/getInviteCode")
	//	public Response<List<InviteCode>> getCode(){
	//		// 检查邀请码是否正确
	//		List<InviteCode> validCodes = getAllInviteCode(inviteCodeDao);
	//		return  Response.success(validCodes);
	//	}
	//
	//	public static List<InviteCode> getAllInviteCode(InviteCodeDao inviteCodeDao) {
	//		List<InviteCode> validCodes = inviteCodeDao.findAll((Specification<InviteCode>) (root, query, cb) -> {
	//			Path<Object> valid = root.get("valid");
	//			return cb.equal(valid, "1");
	//		});
	//		System.out.println(validCodes.toString());
	//		return validCodes;
	//	}
}
